<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
    class="purchase-order-dialog"
    :modal-append-to-body="false"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单号" prop="orderNumber">
            <el-input 
              v-model="form.orderNumber" 
              placeholder="请输入订单号" 
              class="form-input"
              :disabled="!!editingOrder"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select 
              v-model="form.supplierId" 
              placeholder="请选择供应商" 
              style="width: 100%" 
              class="form-select"
              :disabled="!!editingOrder"
            >
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="下单日期" prop="orderDate">
            <el-date-picker
              v-model="form.orderDate"
              type="date"
              placeholder="请选择下单日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              class="form-date-picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计到货日期" prop="expectedDeliveryDate">
            <el-date-picker
              v-model="form.expectedDeliveryDate"
              type="date"
              placeholder="请选择预计到货日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              class="form-date-picker"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购员" prop="purchaser">
            <el-input 
              v-model="form.purchaser" 
              placeholder="请输入采购员" 
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择状态" 
              style="width: 100%" 
              class="form-select"
            >
              <el-option label="待确认" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="采购中" value="purchasing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
          class="form-textarea"
        />
      </el-form-item>
      
      <el-divider />
      
      <div class="order-items-section">
        <div class="section-header">
          <span class="section-title">订单明细</span>
          <el-button 
            type="primary" 
            :icon="Plus" 
            @click="addItem"
            class="add-item-btn"
          >
            添加商品
          </el-button>
        </div>
        
        <el-table :data="form.items" class="order-items-table">
          <el-table-column label="商品名称" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.productName"
                placeholder="商品名称"
                class="table-input"
              />
            </template>
          </el-table-column>
          <el-table-column label="规格" width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.specification"
                placeholder="规格"
                class="table-input"
              />
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                controls-position="right"
                class="table-input-number"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="scope">
              <el-input
                v-model="scope.row.unit"
                placeholder="单位"
                class="table-input"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.unitPrice"
                :min="0"
                :precision="2"
                controls-position="right"
                class="table-input-number"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额" width="100">
            <template #default="scope">
              ¥{{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="备注" width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="备注"
                class="table-input"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="removeItem(scope.$index)"
                class="table-action-btn"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="submit-btn">
          {{ editingOrder ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

interface Supplier {
  id: number
  name: string
}

interface OrderItem {
  id: number
  productName: string
  specification: string
  quantity: number
  unit: string
  unitPrice: number
  amount: number
  remark: string
}

interface PurchaseOrder {
  id: number
  orderNumber: string
  supplierId: number
  supplierName: string
  purchaser: string
  orderDate: string
  expectedDeliveryDate: string
  totalAmount: number
  status: string
  remark: string
  items: OrderItem[]
}

const props = defineProps<{
  modelValue: boolean
  editingOrder: PurchaseOrder | null
  suppliers: Supplier[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', order: PurchaseOrder): void
  (e: 'close'): void
}>()

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  return props.editingOrder ? '编辑采购订单' : '新增采购订单'
})

const form = reactive({
  orderNumber: '',
  supplierId: null as number | null,
  purchaser: '',
  orderDate: '',
  expectedDeliveryDate: '',
  status: 'pending',
  remark: '',
  items: [] as OrderItem[]
})

const rules = {
  orderNumber: [
    { required: true, message: '请输入订单号', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  orderDate: [
    { required: true, message: '请选择下单日期', trigger: 'change' }
  ],
  expectedDeliveryDate: [
    { required: true, message: '请选择预计到货日期', trigger: 'change' }
  ],
  purchaser: [
    { required: true, message: '请输入采购员', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单函数
const resetForm = () => {
  form.orderNumber = ''
  form.supplierId = null
  form.purchaser = ''
  form.orderDate = ''
  form.expectedDeliveryDate = ''
  form.status = 'pending'
  form.remark = ''
  form.items = []
}

// 监听 editingOrder 变化并更新表单
watch(() => props.editingOrder, (newVal) => {
  if (newVal) {
    form.orderNumber = newVal.orderNumber
    form.supplierId = newVal.supplierId
    form.purchaser = newVal.purchaser
    form.orderDate = newVal.orderDate
    form.expectedDeliveryDate = newVal.expectedDeliveryDate
    form.status = newVal.status
    form.remark = newVal.remark
    form.items = [...newVal.items]
  } else {
    resetForm()
  }
}, { immediate: true })

const addItem = () => {
  form.items.push({
    id: Date.now(),
    productName: '',
    specification: '',
    quantity: 1,
    unit: '',
    unitPrice: 0,
    amount: 0,
    remark: ''
  })
}

const removeItem = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除这个商品吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    form.items.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleClose = () => {
  visible.value = false
  emit('close')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      // 模拟提交过程
      setTimeout(() => {
        const orderData: PurchaseOrder = {
          id: props.editingOrder?.id || Date.now(),
          orderNumber: form.orderNumber,
          supplierId: form.supplierId!,
          supplierName: props.suppliers.find(s => s.id === form.supplierId)?.name || '',
          purchaser: form.purchaser,
          orderDate: form.orderDate,
          expectedDeliveryDate: form.expectedDeliveryDate,
          totalAmount: form.items.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0),
          status: form.status,
          remark: form.remark,
          items: [...form.items]
        }
        
        emit('submit', orderData)
        submitLoading.value = false
        ElMessage.success(`${props.editingOrder ? '更新' : '创建'}采购订单成功`)
        handleClose()
      }, 1000)
    } else {
      ElMessage.error('请填写必填项')
    }
  })
}
</script>

<style scoped>
.purchase-order-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.order-items-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.el-divider {
  margin: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-date-picker:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 开关组件特殊样式 */
.form-switch {
  transition: all 0.3s ease;
}

.form-switch:hover {
  transform: scale(1.1);
}

/* 表格输入框悬停效果 */
.table-input:hover,
.table-input-number:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 表格操作按钮悬停效果 */
.table-action-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-action-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 添加商品按钮悬停效果 */
.add-item-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.add-item-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 取消按钮悬停效果 */
.cancel-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.cancel-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 提交按钮悬停效果 */
.submit-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .purchase-order-dialog {
    width: 95% !important;
    margin-top: 20px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-col {
    width: 100%;
  }
  
  .order-items-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>